package com.sinog.front.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;

/**
 * @desc sm4身份证加密解密工具类
 * @author lzq
 * @date -
 */
@Slf4j
public final class Sm4 {

    private static final byte[] DECRYPT_DATA = new byte[0];
    private static final String ENCODING = "UTF-8";
    private static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    /**
     * 定义分组加密模式使用：PKCS5Padding
     */
    private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    /**
     * 128-32位16进制；256-64位16进制
     */
    private static final int DEFAULT_KEY_SIZE = 128;

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 自动生成密钥
     * @return String
     */
    public static String generateKey() throws Exception {
        return new String(Hex.encodeHex(generateKey(DEFAULT_KEY_SIZE),false));
    }

    /**
     * 描述
     * @param keySize keySize
     * @return byte[]
     */
    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME,BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize,new SecureRandom());
        return kg.generateKey().getEncoded();
    }

    /**
     * 生成ECB暗号 ECB模式（电子密码本模式：Electronic codebook）
     * @param algorithmName 算法名称
     * @param mode 模式
     * @param key key
     * @return Cipher
     */
    private static Cipher generateEcbCipher(String algorithmName,int mode,byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName,BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key,ALGORITHM_NAME);
        cipher.init(mode,sm4Key);
        return cipher;
    }

    /**
     * sm4加密 加密模式：ECB
     * @param hexKey 16进制密钥（忽略大小写）
     * @param paramStr 待加密字符串
     * @return 返回16进制的加密字符串
     * 密文长度不固定，会随着被加密字符串长度的变化而变化
     */
    public static String encryptEcb(String hexKey,String paramStr) {
        hexKey = "28AC7D6E85A1A5F8EC0ADCA1BF00631A";
        //添加的
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        try {
            String cipherText;
            // 16进制字符串--&gt;byte[]
            byte[] keyData = ByteUtils.fromHexString(hexKey);
            // String--&gt;byte[]
            byte[] srcData = paramStr.getBytes(ENCODING);
            // 加密后的数组
            byte[] cipherArray = encryptEcbPadding(keyData,srcData);
            // byte[]--&gt;hexString
            cipherText = ByteUtils.toHexString(cipherArray);
            return cipherText;
        } catch(Exception e) {
            log.error(e.getMessage());
            return paramStr;
        }
    }

    /**
     * 加密模式之Ecb
     * @param key key
     * @param data data
     * @return byte[]
     */
    private static byte[] encryptEcbPadding(byte[] key,byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING,Cipher.ENCRYPT_MODE,key);
        return cipher.doFinal(data);
    }

    /**
     * sm4解密 采用ECB
     * @param hexKey 16进制密钥
     * @param cipherText 16进制的加密字符串（忽略大小写）
     * @return 解密后的字符串
     */
    public static String decryptEcb(String hexKey,String cipherText) {
        hexKey = "28AC7D6E85A1A5F8EC0ADCA1BF00631A";
        //添加的
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        // 用于接收解密后的字符串
        String decryptStr = "";
        // hexString--&gt;byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // hexString--&gt;byte[]
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] srcData;
        try {
            srcData = decryptEcbPadding(keyData,cipherData);
            // byte[]--&gt;String
            decryptStr = new String(srcData,ENCODING);
        } catch(IllegalBlockSizeException e) {
            return cipherText;
        } catch(Exception e) {
            log.error("发生异常:",e);
        }
        return decryptStr;
    }

    /**
     * 解密
     * @param key key
     * @param cipherText cipherText
     * @return byte[]
     */
    private static byte[] decryptEcbPadding(byte[] key,byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING,Cipher.DECRYPT_MODE,key);
        return cipher.doFinal(cipherText);
    }

    /**
     * 校验加密前后的字符串是否为同一数据
     * @param hexKey 16进制密钥（忽略大小写）
     * @param cipherText 16进制加密后的字符串
     * @param paramStr 加密前的字符串
     * @return 是否为同一数据
     */
    public static boolean verifyEcb(String hexKey,String cipherText,String paramStr) throws UnsupportedEncodingException {
        // 用于接收校验结果
        boolean flag;
        // hexString--&gt;byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // 将16进制字符串转换成数组
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] decryptData = DECRYPT_DATA;
        try {
            decryptData = decryptEcbPadding(keyData,cipherData);
        } catch(Exception e) {
            log.error("发生异常:",e);
        }
        // 将原字符串转换成byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 判断2个数组是否一致
        flag = Arrays.equals(decryptData,srcData);
        return flag;
    }
}